class MyPromise {
	//类就有构造函数,初始化时候传递了一个立即执行的方法
	//方法有resolve和reject两个方法参数
	constructor(fn) {
		fn(this.resolve, this.reject)
	}
	status = 'PENDING';
	successStr = undefined; //成功返回值
	successCallback = []; //同步时候then返回参数
	failCallback = []; //同步时候then返回参数
	resolveList = []; //处理异步时候处理第二个then返回参数
	rejectList = []; //处理异步时候处理第二个then返回参数
	newPromise = undefined; //then返回的promise对象
	resolve = (str) => {
		//声明初始化需要的成功回调函数
		if (this.status !== 'PENDING') return
		//修改当前状态为PENDING，修改状态为成功
		this.status = "SUCCESS"
		this.successStr = str;
		while (this.successCallback.length) {
			//处理首个then
			this.successStr = this.successCallback.shift()(this.successStr);
		}
		setTimeout((data) => {
			//异步获取返回值,然后把新的promise回调函数返回
			while (this.resolveList.length) {
				resolvePromise(this, this.successStr, this.resolveList.shift(), this.rejectList.shift())
			}
		})
	}
	reject = (str) => {
		//声明初始化需要的失败回调函数
		if (this.status !== 'PENDING') return
		this.status = "FAIL";
		this.successStr = str;
		while (this.failCallback.length) {
			//处理首个then
			this.successStr = this.failCallback.shift()(this.successStr);
		}
		setTimeout(() => {
			//异步获取返回值,然后把新的promise回调函数返回
			while (this.rejectList.length) {
				resolvePromise(this, this.successStr, this.resolveList.shift(), this.rejectList.shift())
			}
		})
	}
	then = (successCallback, failCallback) => {
		this.newPromise = new MyPromise((resolve, reject) => {
			if (this.status == "SUCCESS") {
				let x = successCallback(this.successStr)
				resolvePromise(this, x, successCallback, failCallback)
			} else if (this.status == "FAIL") {
				let x = failCallback(this.failStr);
				resolvePromise(this, x, successCallback, failCallback)
			} else {
				//存储初始化成功失败回调
				successCallback && this.successCallback.push(successCallback);
				failCallback && this.failCallback.push(failCallback);
				//存储then成功失败回调
				resolve && this.resolveList.push(resolve);
				reject && this.rejectList.push(reject);
			}
		})
		return this.newPromise
	}
}

function resolvePromise(vm, x, resolve, reject) {
	if (vm.newPromise === x) {
		throw new Error("不允许返回自身")
		return
	}
	if (x instanceof MyPromise) {
		x.then(resolve, reject)
	} else {
		if (resolve) {
			resolve(x)
		}
		if (reject) {
			reject(x)
		}
	}
}
export default MyPromise
